package com.juxing.service.liveCenter.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.juxing.sdk.util.StringUtil;
import com.juxing.service.liveCenter.ILiveCenterService;
import com.juxing.service.liveCenter.bean.LiveBean;
import com.juxing.service.liveCenter.bean.LiveStreamBean;
import com.juxing.service.liveCenter.cache.ILiveCache;
import com.juxing.service.liveCenter.cache.ILiveStreamCache;
import com.juxing.service.liveCenter.dao.ILiveDao;
import com.juxing.service.liveCenter.dao.ILiveStreamDao;
import com.juxing.service.liveCenter.helper.PiliHelper;

/**
 * 
 * @author brochen
 * @mail mongibello@163.com
 * @created 2016年1月31日
 *
 */
public class LiveCenterServiceImpl implements ILiveCenterService {

	private static final Logger logger = LoggerFactory
			.getLogger(LiveCenterServiceImpl.class);
	
	@Autowired
	private PiliHelper piliHelper;
	
	@Autowired
	private ILiveDao liveDao;
	@Autowired
	private ILiveStreamDao liveStreamDao;
	
	@Autowired
	private ILiveCache liveCache;
	@Autowired
	private ILiveStreamCache liveStreamCache;
	
	@Override
	public LiveStreamBean generateStream(int userId) {
		String stream = piliHelper.createStream();
		if(StringUtil.isEmpty(stream)) {
			logger.warn("can not create live stream.[userId={}]", userId);
			return null;
		}
		
		//插入直播流
		LiveStreamBean liveStreamBean = new LiveStreamBean();
		liveStreamBean.setStream(stream);
		long streamId = liveStreamDao.insert(liveStreamBean);
		if(streamId <= 0) {
			logger.warn("can not insert live stream.[userId={}]", userId);
			return null;
		}
		liveStreamCache.setLiveStream(liveStreamBean);
		return liveStreamBean;
	}

	@Override
	public LiveBean startLive(LiveBean liveBean) {
		logger.debug("startLive userId={}, title={}, scenceId={}",
				liveBean.getUserId(), liveBean.getTitle(),
				liveBean.getScenceId());
		
		//插入直播
		long liveId = liveDao.insert(liveBean);
		if(liveId <= 0) {
			logger.warn("can not insert live.[userId={}]", liveBean.getUserId());
			return null;
		}
		//插入缓存
		liveCache.setLive(liveBean);

		return liveBean;
	}
	@Override
	public LiveBean queryLiveBean(long id) {
		LiveBean bean = liveCache.getLive(id);
		if(bean == null) {
			bean = liveDao.queryById(id);
			if(bean != null) {
				liveCache.setLive(bean);
			}
		}
		
		return bean;
	}
	@Override
	public LiveStreamBean queryLiveStreamBean(long id) {
		LiveStreamBean bean = liveStreamCache.getLiveStream(id);
		if(bean == null) {
			bean = liveStreamCache.getLiveStream(id);
			if(bean != null) {
				liveStreamCache.setLiveStream(bean);
			}
		}
		return bean;
	}
	@Override
	public List<LiveBean> queryActivityLiveList(int activityId) {
		return liveDao.queryLiveByActivityId(activityId);
	}
}
